//
//  MapTableViewCell.m
//  BigToBig
//
//  Created by 毛丽媛 on 16/8/1.
//  Copyright © 2016年 cn.cloudtp. All rights reserved.
//

#import "MapTableViewCell.h"

@implementation MapTableViewCell


- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self createSubViews];
    }
    return self;
}

- (void)createSubViews{
    _mapView =[[MKMapView alloc]init];
    _mapView.zoomEnabled = YES;
    _mapView.showsUserLocation = YES;
    _mapView.scrollEnabled = YES;
    _mapView.delegate = self;
    [self.contentView addSubview:_mapView];
    if([[UIDevice currentDevice].systemVersion floatValue] > 8.0f)
    {
        _geocoder=[[CLGeocoder alloc]init];
        // 定位的地址
        [self getCoordinateByAddress:@"大连港兴路6号万达中心"];
    }
    
    // 长按手势  长按添加大头针
//    UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(lpgrClick:)];
//    [_mapView addGestureRecognizer:lpgr];
}

#pragma mark 根据地名确定地理坐标
-(void)getCoordinateByAddress:(NSString *)address{
    //地理编码
    [_geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {
        //取得第一个地标，地标中存储了详细的地址信息，注意：一个地名可能搜索出多个地址
        NSLog(@"%ld",placemarks.count);
        CLPlacemark *placemark=[placemarks firstObject];
        MKPlacemark *mkplacemark=[[MKPlacemark alloc]initWithPlacemark:placemark];//定位地标转化为地图的地标
        [_mapView setCenterCoordinate:mkplacemark.coordinate animated:YES];
        //设定显示范围
        MKCoordinateSpan theSpan;
        theSpan.latitudeDelta=0.001;
        theSpan.longitudeDelta=0.001;
        //设置地图显示的中心及范围
        MKCoordinateRegion theRegion;
        theRegion.center=mkplacemark.coordinate;
        theRegion.span=theSpan;
        [_mapView setRegion:theRegion];
        location = mkplacemark.location;
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        
        [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *array, NSError *error)
         {
             CLGeocoder *geocoder = [[CLGeocoder alloc] init];
             [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *array, NSError *error) {
                 
                 if (array.count > 0)
                 {
                     CLPlacemark *placemark = [array objectAtIndex:0];
                     // 将获得的所有信息显示到label上
                     NSLog(@"%@",placemark.administrativeArea);
                     // 获取城市
                     NSString *city = placemark.administrativeArea;
                     if (!city) {
                         // 四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                         city = placemark.administrativeArea;
                     }
                     NSLog(@"当前城市:%@",city);
                     // 设置地图显示的类型及根据范围进行显示  安放大头针
                     MKPointAnnotation *pinAnnotation = [[MKPointAnnotation alloc] init];
                     pinAnnotation.coordinate = mkplacemark.coordinate;
                     pinAnnotation.title = city;
                     
                     //                     [_mapView addAnnotation:pinAnnotation];
                     [self addAnnotationWithCoordinate:mkplacemark.coordinate];
                 }
                 else if (error == nil && [array count] == 0)
                 {
                     NSLog(@"No results were returned.");
                 }
                 else if (error != nil)
                 {
                     NSLog(@"An error occurred = %@", error);
                 }
                 
                 
             }];
             
         }];
    }];
}

#pragma mark 添加大头针
-(void)addAnnotationWithCoordinate:(CLLocationCoordinate2D)location{
    LYAnnotation *annotation1=[[LYAnnotation alloc]init];

    annotation1.title=@"大连港兴路6号万达中心";
    annotation1.subtitle=@"18842674213";
    annotation1.coordinate=location;
    annotation1.image=[UIImage imageNamed:@"定位"];
//    annotation1.locationPic.image = [UIImage imageNamed:@""];
//    annotation1.phonePic.image = [UIImage imageNamed:@""];
    [_mapView addAnnotation:annotation1];
    
    
}

// 每次添加大头针都会调用此方法  可以设置大头针的样式
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    
    
    //由于当前位置的标注也是一个大头针，所以此时需要判断，此代理方法返回nil使用默认大头针视图
    if ([annotation isKindOfClass:[LYAnnotation class]]) {
        static NSString *key1=@"AnnotationKey1";
        MKAnnotationView *annotationView=[_mapView dequeueReusableAnnotationViewWithIdentifier:key1];
        //如果缓存池中不存在则新建
        if (!annotationView) {
            annotationView=[[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:key1];
            annotationView.canShowCallout=true;//允许交互点击
            annotationView.calloutOffset=CGPointMake(0, 1);//定义详情视图偏移量
            annotationView.leftCalloutAccessoryView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"weizhi"]];//定义详情左侧视图
        }
        
        //修改大头针视图
        //重新设置此类大头针视图的大头针模型(因为有可能是从缓存池中取出来的，位置是放到缓存池时的位置)
        annotationView.annotation=annotation;
        annotationView.image=((LYAnnotation *)annotation).image;//设置大头针视图的图片
        
        return annotationView;
    }else {
        return nil;
    }
}

//长按添加大头针事件
- (void)lpgrClick:(UILongPressGestureRecognizer *)lpgr
{
    // 判断只在长按的起始点下落大头针
    if(lpgr.state == UIGestureRecognizerStateBegan)
    {
        // 首先获取点
        CGPoint point = [lpgr locationInView:_mapView];
        // 将一个点转化为经纬度坐标
        CLLocationCoordinate2D center = [_mapView convertPoint:point toCoordinateFromView:_mapView];
        [self addAnnotationWithCoordinate:center];
    }
}

- (void)layoutSubviews{
    _mapView.frame = self.contentView.bounds;
}

//计算两个位置之间的距离
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
